package com.shouru.server;

import java.io.File;
import java.io.IOException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer extends AbstarctServer {

	private Server server;
	private final WebAppContext webapp = new WebAppContext();

	@Override
	protected void doStart() {
		server = new Server();
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(getPort());
		server.addConnector(connector);
		webapp.setThrowUnavailableOnStartupException(true);
		webapp.setContextPath(getContext());
		webapp.setResourceBase(getWebAppDir());
		webapp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
		webapp.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		server.setHandler(webapp);
		changeClassLoader(webapp);

		try {
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}

	}

	@Override
	protected void doStop() {
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void changeClassLoader(WebAppContext webapp) {
		try {
			webapp.setClassLoader(new WebAppClassLoader(webapp));
		} catch (IOException e1) {
			throw new IllegalStateException(e1);
		}
	}

	class WebAppClassLoader extends org.eclipse.jetty.webapp.WebAppClassLoader {
		public WebAppClassLoader(WebAppContext context) throws IOException {
			super(context);
			for (String path : getClassPath().split(String.valueOf(File.pathSeparatorChar))) {
				if (path.startsWith("-y-") || path.startsWith("-n-")) {
					path = path.substring(3);
				}

				if (path.startsWith("-n-") == false) {
					super.addClassPath(path);
				}
			}
		}

		private String getClassPath() {
			return System.getProperty("java.class.path");
		}
	}

	@Override
	protected void serverJoin() {
		try {
			server.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onChange() {
		try {
			webapp.stop();
			changeClassLoader(webapp);
			webapp.start();
			System.out.println("服务器重启成功.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
}